<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewpoint" content="width=device,initial-scale=1">
  <link href="font-awesome-4.7.0/css/font-awesome.css" rel="stylesheet">
  <link href="reset.css" rel="stylesheet">
  <link href="icon.css" rel="stylesheet">
  <link href="order.css" rel="stylesheet">
  <title>饿了么 确认订单</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
</head>

<body>
  <div class="wrapper">
    <!--  header部分-->
    <header>
      <p>确认订单</p>
    </header>
    <!--  订单信息部分-->
    <div class="order-info">
      <h5>订单配送至:</h5>
      <div class="order-info-address">
        <p>云南大学呈贡校区</p>
        <!--      表示一个向右的箭头-->
        <i class="fa fa-angle-right"></i>
      </div>
      <p id="userInfo">李梦菲女士 123456789</p>
    </div>
    <h3 id="businessName"></h3>
    <!--  订单明细部分-->
    <ul class="order-detailed">
    </ul>
    <div class="order-deliveryfee">
      <p>配送费</p>
      <p>&#165;<span id="deliveryPrice"></span></p>
    </div>
    <!-- 合计部分 -->
    <div class="total">
      <div class="total-left">
        &#165;<span id="totalPrice"></span>
      </div>
      <div class="total-right" onclick="toPay()">
        去支付
      </div>
    </div>
  </div>
</body>

<script>
  // 页面加载时从 localStorage 获取选择的地址和用户信息
  $(document).ready(function () {
    var selectedAddress = localStorage.getItem('selectedAddress');
    var selectedUser = localStorage.getItem('selectedUser');

    if (selectedAddress) {
      $('#selectedAddress').text(selectedAddress);
    }
    if (selectedUser) {
      $('#userInfo').text(selectedUser);
    }

    var shopId = getURLParameter('shopId');
    if (shopId == null || shopId == '') {
      alert('参数错误');
      return;
    }
    var userInfo = getUserInfo();
    console.log(userInfo);
    listCarts(shopId);
  });

  function getURLParameter(name) {
    // 获取 URL 中的查询字符串部分
    var urlParams = new URLSearchParams(window.location.search);
    // 返回指定参数的值
    return urlParams.get(name);
  }

  function getUserInfo() {
    // 从 cookie 中读取用户信息
    var userInfoString = $.cookie('userInfo');
    if (userInfoString) {
      return JSON.parse(userInfoString);
    } else {
      window.location.href = 'login.html';
    }
  }

  function listCarts(shopId) {
    $.ajax({
      url: 'http://127.0.0.1:8081/cart/listCart',
      type: 'POST',
      contentType: 'application/json; charset=UTF-8', // 设置内容类型为 JSON
      data: JSON.stringify({
        userId: getUserInfo().userId,
        shopId: shopId
      }),
      success: function (res) {
        if (res.flag) {
          console.log(res)
          $('#businessName').text(res.data[0].shop.shopName);
          $('#deliveryPrice').text(res.data[0].shop.deliveryPrice);
          var totalPrice = res.data[0].shop.deliveryPrice;
          var html = []
          for (var i = 0; i < res.data.length; i++) {
            html.push('<li>                              ')
            html.push('	<div class="order-detailed-left">')
            html.push('	  <img src="' + res.data[i].food.foodImg + '">       ')
            html.push('	  <p>' + res.data[i].food.foodName + ' x ' + res.data[i].quantity + '</p>      ')
            html.push('	</div>                           ')
            html.push('	<p>&#165;' + (res.data[i].food.foodPrice * res.data[i].quantity) + '</p>                  ')
            html.push('</li>                             ')
            totalPrice += res.data[i].food.foodPrice * res.data[i].quantity;
          }
          $('.order-detailed').html(html.join(''))
          $('#totalPrice').text(totalPrice)
        } else {
          alert(res.message)
        }
      },
      error: function (xhr, status, error) {
        alert('查询失败：' + xhr.statusText);
      }
    });
  }

  function createOrder(userId, shopId) {
    $.ajax({
      url: 'http://127.0.0.1:8081/order/createOrder?userId=' + userId + '&shopId=' + shopId + '&da=1',
      type: 'POST',
      contentType: 'application/json; charset=UTF-8', // 设置内容类型为 JSON
      success: function (res) {
        if (res.flag) {
          console.log(res)
          window.location.href = 'payment.html?orderId=' + res.data
        } else {
          alert(res.message)
        }
      },
      error: function (xhr, status, error) {
        alert('查询失败：' + xhr.statusText);
      }
    });
  }

  function toPay() {
    var userInfo = getUserInfo();
    if (parseInt($("#totalPrice").text()) > 0) {
      createOrder(userInfo.userId, getURLParameter('shopId'));
    } else {
      alert('请先选购菜品');
    }
  }

  $(document).ready(function () {
    var shopId = getURLParameter('shopId');
    if (shopId == null || shopId == '') {
      alert('参数错误');
      return;
    }
    var userInfo = getUserInfo();
    console.log(userInfo);
    $('#userInfo').text(userInfo.userName + (userInfo.userSex == '1' ? '先生' : '女士') + ' ' + userInfo.userId);
    listCarts(shopId);
  });
</script>

</html>